import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework_jwt.settings import api_settings

from questions.models import Questions
from .models import User, Homepage, Archives


# from .models import Homepage


class CreateUserSerializer(serializers.ModelSerializer):
    """创建用户序列化器"""
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)
    token = serializers.CharField(label="JWT token", read_only=True)

    class Meta:
        model = User
        fields = ["id", "username", "password", "sms_code",
                  "mobile", "allow", "token"]
        extra_kwargs = {
            "username": {
                "min_length": 5,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许5-20个字符的用户名",
                    "max_length": "仅允许5-20个字符的用户名",
                }
            },
            "password": {
                "write_only": True,
                "min_length": 6,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许6-20个字符的密码",
                    "max_length": "仅允许6-20个字符的密码",
                }
            }

        }

    def validate_mobile(self, mobile):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError("手机号格式不正确")
        return mobile

    def validate_allow(self, allow):
        """验证是否同意协议"""
        if allow != "true":
            raise serializers.ValidationError("请同意协议")
        return allow

    def validate(self, attrs):

        # 判断短信验证码
        redis_conn = get_redis_connection("verify_codes")
        mobile = attrs["mobile"]
        real_sms_code = redis_conn.get("sms_%s" % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError("无效的短信验证码")
        if attrs["sms_code"] != real_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        return attrs

    def create(self, validated_data):
        """创建用户"""

        # 移除数据库模型类中不存在的属性
        del validated_data["sms_code"]
        del validated_data["allow"]

        # user = User.objects.create(**validated_data)
        user = super().create(validated_data)
        # 调用django的认证系统加密密码
        user.set_password(validated_data["password"])
        user.save()

        # 补充签发生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user

class UsermobileSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
#
class HomepageSerializer(serializers.ModelSerializer):

    user= UsermobileSerializer()
    """用户主页"""
    class Meta:
        model = Homepage
        fields = '__all__'
#

class ArchivesSerializer(serializers.ModelSerializer):
    '''
    用户档案
    '''
    user = UsermobileSerializer()
    class Meta:
        model = Archives
        fields = '__all__'







class MyQuestionsSerializer(serializers.ModelSerializer):
    """
    返回我的问题
    """
    class Meta:
        model = Questions
        fields = '__all__'